import React, { useEffect, useState, useMemo } from "react";
import {
  View,
  Text,
  StyleSheet,
  Platform,
  StatusBar,
  TouchableOpacity,
  ScrollView,
  FlatList,
  Alert,
  Modal,
} from "react-native";
import SingleSelect from "../../components/SingleSelect";
import MultiSelect from "../../components/MultiSelect";
import query from "../../api/query";
import AsyncStorage from "@react-native-async-storage/async-storage";
import NoData from "../../components/preAdmin/NoData";
import { useSelector } from "react-redux";
import LoadingBar from "../../components/InterView/LoadingBar";

const Testing = ({ navigation }) => {
  const [allQuestions, setAllQuestions] = useState([]);
  const [title, setTitle] = useState(null);
  const [testId, setTestId] = useState(null);
  const [isTestVisible, setIsTestVisible] = useState(false); //试卷是否可见
  const user = useSelector((state) => state.authR.user);
  const [isVisible, setIsVisible] = useState(false); //分数弹出框
  const [isScoreVisible, setIsScoreVisible] = useState(false);
  const [correctNum, setCorrectNum] = useState(null);
  const [score, setScore] = useState(null);
  const [isLoading, setIsLoading] = useState(false);
  useEffect(() => {
    const fetchData = async () => {
      try {
        setIsLoading(true);
        const token = await AsyncStorage.getItem("token");
        const result = await query.get("/test/publish", {
          headers: { Authorization: token },
        });

        if (result.data.data !== 0) {
          const res = await query.get(
            "/score/test/" + result.data.data[0]._id,
            {
              headers: { Authorization: token },
            }
          );
          setAllQuestions(result.data.data[0].questions);
          setTitle(result.data.data[0].title);
          setTestId(result.data.data[0]._id);
          const score = res.data.data.filter(
            (item) => item.userId === user._id
          );
          if (score.length !== 0) {
            setScore(score[0].score);
            setIsScoreVisible(true);
            setIsTestVisible(false);
          } else {
            setIsScoreVisible(false);
            setIsTestVisible(true);
          }
        }
      } catch (err) {
        console.log("初始化试卷出错", err);
      }
      setIsLoading(false);
    };
    fetchData();
  }, []);

  let corretAnswers = new Array(allQuestions.length).fill(0);

  const onSingleChoosed = (data, index) => {
    if (data === undefined || data.length === 0) {
      return;
    }
    if (data[0].id === allQuestions[index].correntOption[0]) {
      corretAnswers[index] = 1;
    } else {
      corretAnswers[index] = 0;
    }
  };

  const onMultiChoosed = (data, index) => {
    if (data === undefined || data.length === 0) {
      return;
    }
    let selected = [];
    data.map((item) => selected.push(item.id));
    if (
      selected.sort().toString() ===
      allQuestions[index].correntOption.sort().toString()
    ) {
      corretAnswers[index] = 1;
    } else {
      corretAnswers[index] = 0;
    }
  };

  const onSummit = () => {
    Alert.alert("提示", "确定要提交(只有一次提交机会)吗?", [
      {
        text: "取消",
        style: "cancel",
      },
      {
        text: "确定",
        onPress: async () => {
          setIsLoading(true);
          const result = corretAnswers.filter((item) => {
            return item == 1;
          });
          setCorrectNum(result.length);
          let item = {
            testId: testId,
            userId: user._id,
            score: result.length + "/" + allQuestions.length,
          };

          try {
            const token = await AsyncStorage.getItem("token");
            const result = await query.post("/score", item, {
              headers: { Authorization: token },
            });
            setIsVisible(true);
            setScore(result.data.data.score);
          } catch (err) {
            console.log("提交试卷失败", err);
            Alert.alert("", "提交试卷失败");
          }
          setIsLoading(false);
        },
      },
    ]);
  };

  return (
    <View style={styles.container}>
      <LoadingBar visible={isLoading} />
      {isTestVisible && (
        <FlatList
          style={{ flex: 1 }}
          removeClippedSubviews={false}
          initialNumToRender={allQuestions.length}
          listKey={"Main"}
          ListHeaderComponent={
            <Text style={{ fontSize: 18, textAlign: "center", marginTop: 10 }}>
              {title}
            </Text>
          }
          data={allQuestions}
          keyExtractor={(item, index) => {
            return item._id; //remember to use return when using {}bracket
          }} //otherwise it will not work
          renderItem={({ item, index }) => {
            return (
              <View key={index} style={styles.question}>
                <View>
                  <Text style={{ fontSize: 16 }}>
                    <Text
                      style={{
                        fontSize: 18,
                        color: "#3ABEF0",

                        fontWeight: "bold",
                      }}
                    >
                      {index + 1}
                    </Text>
                    <Text style={{ color: "#797979", fontSize: 16 }}>
                      /{allQuestions.length}
                    </Text>

                    <Text
                      style={{
                        color: "#3ABEF0",
                        fontSize: 14,
                        fontWeight: "bold",
                      }}
                    >
                      {item.type == "singleSelect" ? " [单选] " : " [多选] "}
                    </Text>

                    {item.question}
                  </Text>
                </View>
                {item.type == "singleSelect" ? (
                  <SingleSelect
                    data={item.options}
                    onChangeDatasChoosed={(data) => {
                      onSingleChoosed(data, index);
                    }}
                  />
                ) : (
                  <MultiSelect
                    data={item.options}
                    onChangeDatasChoosed={(data) => {
                      onMultiChoosed(data, index);
                    }}
                  />
                )}
              </View>
            );
          }}
        />
      )}

      {allQuestions.length !== 0 && isTestVisible && (
        <TouchableOpacity style={styles.Button} onPress={() => onSummit()}>
          <Text style={styles.Text}>提交</Text>
        </TouchableOpacity>
      )}

      {isScoreVisible && (
        <View style={styles.scoreCard}>
          <Text style={styles.scoreText}>{title}</Text>
          <Text style={styles.scoreText}>已完成</Text>
          <Text style={styles.scoreText}>{score}</Text>
        </View>
      )}

      {!isTestVisible && !isScoreVisible && <NoData />}

      <Modal animationType="fade" transparent={true} visible={isVisible}>
        <View style={styles.modalBackground}></View>
        <View style={styles.centeredView}>
          <View style={styles.modalView}>
            <Text style={{ fontSize: 18 }}>
              你的成绩为
              <Text
                style={{
                  fontSize: 20,
                  fontWeight: "bold",
                  color: "#4fe14f",
                }}
              >
                {correctNum}
              </Text>
              <Text>/{allQuestions.length}!</Text>
            </Text>
            <View style={{ padding: 10 }}>
              <Text style={{ fontSize: 14, color: "#727272" }}>
                下次再接再厉!
              </Text>
            </View>
            <TouchableOpacity
              style={styles.confirmButton}
              onPress={() => {
                setIsVisible(false);
                setIsTestVisible(false);
                setIsScoreVisible(true);
              }}
            >
              <Text>确定</Text>
            </TouchableOpacity>
          </View>
        </View>
      </Modal>
    </View>
  );
};

var styles = StyleSheet.create({
  container: {
    // height: "100%",
    backgroundColor: "#f5f5f5",
    flex: 1,
    // padding: 16,
  },
  question: {
    padding: 16,
    margin: 14,
    backgroundColor: "#fff",
    borderRadius: 2,
  },

  Button: {
    borderRadius: 5,
    margin: 18,
    padding: 10,
    backgroundColor: "#3ABEF0",
    alignItems: "center",
    justifyContent: "center",
    elevation: 2, //设置阴影角度，通过这个设置有无阴影
    shadowColor: "gray", // 设置阴影色
  },
  Text: {
    fontSize: 16,
    color: "#fff",
    fontWeight: "bold",
  },
  modalBackground: {
    backgroundColor: "#727272",
    opacity: 0.3,
    zIndex: 0,
    position: "absolute",
    width: "100%",
    height: "100%",
  },
  centeredView: {
    flex: 1,
    alignItems: "center",
    justifyContent: "center",
  },
  modalView: {
    backgroundColor: "#fff",
    width: "80%",
    height: "25%",
    alignItems: "center",
    justifyContent: "center",
    borderRadius: 2,
    elevation: 2, //设置阴影角度，通过这个设置有无阴影
    shadowColor: "gray", // 设置阴影色
  },
  confirmButton: {
    borderRadius: 5,
    marginTop: 10,
    padding: 5,
    paddingLeft: 20,
    paddingRight: 20,
    borderColor: "#3ABEF0",
    borderWidth: 1,
    alignItems: "center",
    justifyContent: "center",
  },
  scoreCard: {
    flexDirection: "row",
    padding: 10,
    backgroundColor: "#fff",
    margin: 12,
    borderRadius: 3,
  },
  scoreText: {
    fontSize: 16,
    flex: 1,
    textAlign: "center",
  },
});

export default Testing;
